#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright © 2005-2007 Kaufmann Manuel
#
# This file is part of Tweety-Finger.
#
# Tweety-Finger is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Tweety-Finger is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Tweety-Finger; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  
# USA


import sys
import pygame
import random
from pygame.locals import *
import time
import os

from menu import Menu
from highscores import HighScores
from window import Window


class Game(object):
	def __init__(self, title="", size=(640, 480), bgImage="", icon=""):
		"""
			Contructor de la clase, recibe el titulo
			de la ventana, el tamaño, la imagen de fondo
			y el icono de la aplicacion
		"""
		
		self.window = Window(title, size, bgImage, icon)
		centerx = self.window.screen.get_rect().centerx
		centery = self.window.screen.get_rect().centery - 90
		spacey = 25
		self.window.setHighScorePosition(centerx, centery, spacey)
		
		scoreFont = pygame.font.Font("fonts/acquaint.ttf", 20)
		self.highscores = HighScores(["data/scoresEasy.dat", \
					      "data/scoresMedium.dat", \
					      "data/scoresHard.dat"], \
					      scoreFont, self.window)
		
		self.abc = ""
		self.timeStart = 0
		self.timeFinish = 0
		#self.showMenu()
		
	def backToMenu(self):
		"""
			Detiene el sonido del reloj para volver al menu
		"""
		self.window.clock.stop()
		#self.mainMenu.waitOption()

	def showMenu(self):
		"""
			Crea y muestra el menu principal de la aplicacion
		"""
		
		red = (255,0,0)
		grey = (170, 170, 170)
		screen = self.window.screen
		posx = screen.get_rect().centerx
		posy = screen.get_rect().centery - 50
		spacey = 50
		acquaint25 = pygame.font.Font("fonts/acquaint.ttf", 25)
		acquaint35 = pygame.font.Font("fonts/acquaint.ttf", 40)
		mainMenuOptions = ["Start", "High Scores", "Quit"]
		startMenuOptions = ["Easy", "Medium", "Hard"]
		soundDownMove = pygame.mixer.Sound("sound/downMenu.ogg")
		soundUpMove = pygame.mixer.Sound("sound/upMenu.ogg")
		soundEnter = pygame.mixer.Sound("sound/enterMenu.ogg")
		backImage = pygame.image.load("image/menu.jpg")
		
		self.startMenu = Menu(self.window, acquaint25, acquaint35,\
				 grey, red, posx, posy, spacey, startMenuOptions, \
				 soundUpMove, soundDownMove, soundEnter, \
				 backImage, [None, None, None], [self.main, self.main, self.main])
		
		self.highScoresMenu = Menu(self.window, acquaint25, acquaint35,\
				 grey, red, posx, posy, spacey, startMenuOptions, \
				 soundUpMove, soundDownMove, soundEnter, \
				 backImage, [None, None, None], [self.highscores.showHighScores, self.highscores.showHighScores, self.highscores.showHighScores])
		
		self.mainMenu = Menu(self.window, acquaint25, acquaint35,\
				 grey, red, posx, posy, spacey, mainMenuOptions, \
				 soundUpMove, soundDownMove, soundEnter, \
				 backImage, [self.startMenu, self.highScoresMenu, None], \
				 [None, None, sys.exit])
		
		self.mainMenu.waitOption()

	def highScores(self, option):
		"""
			Muestra los highscores en pantalla
		"""
		
		self.highscores.showHighScores()

	def restart(self):
		"""
			Reinicia el juego
		"""
		
		if self.shuffle:
			random.shuffle(self.letters)
		else:
			self.letters = ["a", "b", "c", "d", "e", "f", "g", \
					"h", "i", "j", "k", "l", "m", "n", \
					"o", "p", "q", "r", "s", "t", "u", \
					"v", "w", "x", "y", "z"]
		self.window.clock.stop()
		self.window.setBackground("main")
		self.window.setLetter(self.letters[0])
		self.abc = ""

	def difficulty(self, option):
		"""
			Setea la dificultad de acuerdo a lo seleccionado
			por el usuario
		"""
		
		self.difficulty = option
		
		if option == "Easy":
			self.shuffle = False
		elif option == "Medium":
			self.shuffle = True
		elif option == "Hard":
			# FIXME: crear otro estilo de juego
			self.shuffle = random.randint(0,1)

	def main(self, option):
		"""
			Bucle principal del juego, espera que el usuario
			presione cualquier tecla
		"""
		
		self.difficulty(option)
		eventType = None
		self.restart()
		while eventType != QUIT:
			event = pygame.event.wait()
			eventType = event.type
			if event.type == KEYDOWN:
				if event.key == K_ESCAPE:
					break
				else:
					self.keyPressed(event)
		if eventType == QUIT:
			self.mainQuit()
		self.backToMenu()

	def mainQuit(self):
		"""
			Sale del juego
		"""
		
		sys.exit("Quit")

	def keyPressed(self, event):
		"""
			Captura los eventos que ejecuta el
			usuario y los maneja
		"""
		if event.key != K_SPACE:
			letter = event.unicode
			if len(self.abc) == 0 and letter == self.letters[0]:
				self.window.clock.play(-1)
				self.timeStart = time.time()
		
			currentLetter = self.letters[len(self.abc)]
			
			if letter == currentLetter:
				self.window.setBackground("game")
				self.window.goodEnter.play()
				self.abc += letter
				if len(self.abc) == 26:
					self.finish()
					#self.backToMenu()
				else:
					currentLetter = self.letters[len(self.abc)]
					self.window.setLetter(currentLetter)
			else:
				self.window.badEnter.play()
		else:
			# Si presiona la barra
			self.restart()

	def finish(self):
		"""
			Termina el juego, muestra el puntaje alcanzado y si
			es un high score pide el nombre y actualiza el archivo
		"""
		
		self.restart()
		self.timeFinish = time.time()
		totalTime = self.timeFinish - self.timeStart
		self.window.showMyScore(str(totalTime))
		self.highscores.difficulty = self.difficulty
		if self.highscores.isHighScore(totalTime):
			#self.window.
			name = self.window.insertName()
			self.highscores.insertHighScore(totalTime, name)